<?php
/**
 * Created by VeryStar.
 * User: Rob
 * Date: 2018/12/10
 * Time: 9:29
 */
namespace Services;

use Admin\Models\school\XhschoolInfo;
use Admin\Models\school\XhschoolSite;
use Admin\Models\user\XhsysUser;
use Helpers\Hrm;
use Helpers\HttpClient;
use Admin\Models\overt\XhovertMsgtemplate;
use Admin\Models\sys\XhsysConfig;
use Admin\Models\sys\XhsysEnum;
use Helpers\Cache;
use Helpers\Main;
use Helpers\User;
use Helpers\UserPower;
use Helpers\XhException;
use Modules\Power;
use Modules\ShortCut;
use Phalcon\Mvc\Controller as PhalconController;

class ConfigManage extends PhalconController
{

    public static $microEnum = [
        'bLong' => [1 => '永久', 2 => '实时'],
        'bShow' => [1 => '是', 2 => '否']
    ];
    public static $httpClient;

    /**
    * 初始化配置
    *
    * @throws XhException
    *
    * create by fyh 20181210
    */
    public static function init()
    {
    }

    /**
     * 短信模版- 获取列表数据
     * @return array|string
     *
     * create by fyh 20181210
     */
    public static function overtGetMsgTemplateData()
    {
        $parameters['conditions'] = 'bDelete = 0';
        $parameters['order'] = 'iAppCode';
        $parameters['columns'] = 'iMTId,iAppCode,sContent';
        $result = Main::runModelPaginator('\\Admin\\Models\\overt\\XhovertMsgtemplate', $parameters, true);
        $data = $result['rows'];
        $appList = XhsysEnum::getEnumByNodeName('应用编号');
        foreach ($data as $key => $value) {
            if ($value['iAppCode']) {
                $data[$key]['sAppName'] = $appList[$value['iAppCode']];
            }
        }
        $result['rows'] = $data;
        return $result;
    }

    /**
     * 短信模版- 新增/更新
     * @param $realData
     * @return XhovertMsgtemplate
     *
     * create by fyh 20181210
     */
    public static function overtModifyMsgTemplate($realData)
    {
        $obj = XhovertMsgtemplate::createRecord($realData);
        if ($obj->iMTId) {
            UserPower::checkUserPower('Overt_MsgTemplate_Edit') or die(Main::showMessageModal('无修改短信模板权限'));
            $obj->updateData() or die(Main::showMessageModal('修改失败！', 109112004));
            Main::createCommitLog('overt', 'MsgTemplate', 'edit', $obj, $obj->iMTId);
        } else {
            UserPower::checkUserPower('Overt_MsgTemplate_Add') or die(Main::showMessageModal('无增加短信模板权限'));
            $obj->insertData() or die(Main::showMessageModal('新增失败！'));
            Main::createCommitLog('overt', 'MsgTemplate', 'add', $obj, $obj->iMTId);
        }
        return $obj;
    }

    /**
     * 短信模版- 删除
     * @param $idArr
     * @return bool
     *
     * create by fyh 20181210
     */
    public static function overtDelMsgTemplate($idArr)
    {
        XhovertMsgtemplate::deleteRecordById($idArr) or die('（109112008）删除失败！');
        Main::createCommitLog('overt', 'MsgTemplate', 'del', ['ids' => $idArr], null, '批量删除');
        return true;
    }


    /**
     * 获取权限
     * @param $tag
     * @return array|bool
     * create by fyh 20181225
     */
    public static function extraPower($tag)
    {
        if (User::isAdmin()) {
            return true;
        }
        $deps = User::getExtraPower('config', $tag);
        $userIds = Hrm::getUserByDepId($deps);
        $newArr = [];
        foreach ($userIds as $ids) {
            $newArr = array_merge($newArr, $ids);
        }
        $newArr = array_values(array_filter($newArr));
        return $newArr;
    }

    /**
     * 配置列表- 获取数据
     * @param $type
     * @param $search
     * @return string
     *
     * create by fyh 20181210
     */
    public static function configDetConfigData($type, $search = [])
    {
        $conditionsArr = [];
        if (!User::isAdmin()) {
            $conditionsArr = [
                'conditions' => "iCreateUserId = :nowUser: and bDelete=0 and sConfigType = '".$type."'",
                'bind'       => ['nowUser' => Main::getLoginUserInfo('userId')]
            ];
            $extraIds = Power::getExtraPower('config', $type);
            if ($extraIds === true) {
                $params = [
                    'columns'    => 'iSCId,sConfigExplain',
                    'conditions' => "bDelete = 0 and sConfigType = '".$type."'"
                ];
                $config = XhsysConfig::find($params)->toArray();
                $config = array_column($config, 'sConfigExplain', 'iSCId');
                $extraIds = array_keys($config);
                $conditionsArr['conditions'] .= " or  (iSCId in ({iSCId:array})  and bDelete=0)";
                $conditionsArr['bind'] = array_merge($conditionsArr['bind'], array('iSCId' => $extraIds));
            } elseif (is_array($extraIds) && !empty($extraIds)) { //有扩展权限
                $conditionsArr['conditions'] .= " or  (iSCId in ({iSCId:array}) 
                and bDelete=0 and sConfigType = :sConfigType:)";
                $conditionsArr['bind'] = array_merge($conditionsArr['bind'], array(
                    'iSCId' => $extraIds, 'sConfigType'=> $type));
            }
        } else {
            if ($type) {
                $conditionsArr['conditions'] = "bDelete=0 and sConfigType = '".$type."'";
            }
        }
        if (isset($search['keyword'])) {
            $conditionsArr['conditions'] .= " and (sConfigExplain like '%".$search['keyword']."%' or 
            sConfigName like '%".$search['keyword']."%' or mConfigValueNew like '%".$search['keyword']."%') ";
        }
        if (isset($search['status'])) {
            $conditionsArr['conditions'] .= " and bStatus = ".$search['status'];
        }
        $result = Main::runModelPaginator('\\Admin\\Models\\sys\\XhsysConfig', $conditionsArr, true);
        foreach ($result['rows'] as $key => $value) {
            $result['rows'][$key]['bStatus'] = $value['bStatus'] ? '禁用' : '启用';
        }
        return json_encode($result);
    }

    /**
     * 配置列表 - 新增/更新
     * @param $realData
     * @return string
     * @throws XhException
     *
     * create by fyh 20181210
     */
    public static function configModifyConfig($realData)
    {
        if ($realData['iSCId']) {
            $extraIds = Power::hasExtra('config', $realData['type'], $realData['iSCId'], true);
            if (!$extraIds) {
                throw new XhException('无权限操作');
            }
        }
        $config = XhsysConfig::createRecord($realData);
        $config->save() or die('（109117002）数据保存失败！');
        Cache::delete('config_' . $config->sConfigName);
        return true;
    }

    /**
     * 配置管理 - 启用/禁用
     * @param $target
     * @param $ids
     * @param $type
     * @return bool
     * @throws XhException
     *
     * create by fyh 20181210
     */
    public function configSetConfigState($target, $ids, $type)
    {
        switch ($target) {
            case 'enable':
                $value = 0;
                break;
            case 'disable':
                $value = 1;
                break;
            default:
                die('（109117004）参数不正确');
        }
        if ($ids) {
            foreach ($ids as $key => $id) {
                $extraIds = Power::hasExtra('config', $type, $id, true);
                if (!$extraIds) {
                    throw new XhException('无权限操作');
                }
            }
        }
        $configs = XhsysConfig::find([
            'conditions' => 'iSCId IN ({iSCId:array}) AND bDelete = 0',
            'bind' => ['iSCId' => $ids]
        ]);
        foreach ($configs as $config) {
            $config->bStatus = $value;
            if (!$config->save()) {
                throw new XhException('操作失败');
            }
        }
        Cache::flush();
        return true;
    }

    /**
     * 配置管理 - 删除
     * @param $ids
     * @param $type
     * @return bool
     * @throws XhException
     *
     * create by fyh 20181210
     */
    public function configDelConfig($ids, $type)
    {
        if ($ids) {
            foreach ($ids as $key => $id) {
                $extraIds = Power::hasExtra('config', $type, $id, true);
                if (!$extraIds) {
                    throw new XhException('无权限操作');
                }
            }
        }
        $configs = XhsysConfig::find([
            'conditions' => 'iSCId IN ({iSCId:array})',
            'bind' => ['iSCId' => $ids]
        ]);
        foreach ($configs as $config) {
            $config->bDelete = 1;
            if (!$config->save()) {
                throw new XhException('操作失败');
            }
        }
        Cache::flush();
        return true;
    }

    /**
     * 快捷键- 管理员分配权限页面
     * @param $iNoId
     * @return string
     *
     * create by fyh 20181210
     */
    public static function manageAdd($iNoId)
    {
        $obj = new ShortCut();
        $data = $obj->shortDetails($iNoId);
        return $data;
    }

    /**
     * 快捷键- 获取数据
     * @param $key
     * @param $public
     * @param $model
     * @return array|string
     *
     * create by fyh 20181211
     */
    public static function manageGetNoAfList($key, $public, $model)
    {
        $short = new ShortCut();
        $data = $short->shortlist($key, $public, $model);
        return $data;
    }

    /**
     * 快捷键- 新增快捷键
     * @param $data
     * @return bool
     * @throws \Exception
     *
     * create by fyh 20181211
     */
    public static function manageSaveShort($data)
    {
        $obj = new ShortCut();
        if (!$data['iNoId']) {
            $isCheck = $obj->checkTag($data['tag']);
            if ($isCheck) {
                throw new XhException('此权限已经存在');
            }
        }
        $obj->insertShortCut(
            $data['logo'],
            $data['name'],
            $data['url'],
            $data['module'],
            $data['openMode'],
            $data['tag'],
            $data['public']
        );
        return true;
    }

    /**
     * 快捷键 - 删除/批量删除
     * @param $ids
     * @return bool
     *
     * create by fyh 20181211
     */
    public static function manageDelShort($ids)
    {
        $short = new ShortCut();
        $reulst = $short->delShortCuts($ids);
        if ($reulst) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 快捷键- 个人设置列表
     * @return array
     *
     * create by fyh 20181211
     */
    public static function manageList()
    {
        $short = new ShortCut();
        $dataList = $short->userShortCuts();
        return $dataList;
    }

    /**
     * 首页设置- 桌面列表
     * @return mixed
     *
     * create by fyh 20181211
     */
    public static function personIndex()
    {
        $short=new ShortCut();
        $dataList = $short->allUserShortCut();
        return $dataList;
    }

    /**
     * 首页设置- 新增/更新快捷桌面
     * @param $ids
     * @param $public
     * @return bool
     *
     * create by fyh 20181211
     */
    public static function personUpdateShort($ids, $public)
    {
        $short = new ShortCut();
        $short->addUserShortCut($ids, $public);
        return true;
    }

    /**
     * 首页设置- 移除快捷桌面
     * @param $ids
     * @param $public
     * @return bool
     *
     * create by fyh 20181211
     */
    public static function personDelShort($ids, $public)
    {
        $short = new ShortCut();
        $short->delUserShort($ids, $public);
        return true;
    }

    /**
     * 平台设置- 智通云白名单 - 获取列表
     * @param $page
     * @param $size
     * @return array
     *
     * create by fyh 20181211
     */
    public static function appServerGetWhiteList($page, $size)
    {
        $config = Main::getConfigByName('jAppServer');
        self::$httpClient = new HttpClient($config['url']);
        $response = self::$httpClient->get(
            '/api/v1/whitelist/',
            ['page' => $page, 'size' => $size]
        );
        $body = $response->toArray();
        return $body;
    }

    /**
     * 平台设置- 智通云白名单 - 新增
     * @param $whiteInfo
     * @throws XhException
     *
     * create by fyh 20181211
     */
    public static function appServerCreateWhiteList($whiteInfo)
    {
        $config = Main::getConfigByName('jAppServer');
        self::$httpClient = new HttpClient($config['url']);
        self::$httpClient->setHeader('Content-Type', 'application/json');
        $response = self::$httpClient->postJson('/api/v1/whitelist/', $whiteInfo);
        if (!$response->isSuccess()) {
            $body = $response->toObject();
            throw new XhException('新增失败', $body->error ?: $response);
        }
    }

    /**
     * 平台设置- 智通云白名单 - 修改状态
     * @param $ids
     * @param $status
     * @throws XhException
     *
     * create by fyh 20181211
     */
    public static function appServerModifyWhiteListStatus($ids, $status)
    {
        $config = Main::getConfigByName('jAppServer');
        self::$httpClient = new HttpClient($config['url']);
        $response = self::$httpClient->put(sprintf('/api/v1/whitelist/%s', $ids[0]), ['status' => $status]);
        if (!$response->isSuccess()) {
            $body = $response->toObject();
            throw new XhException('修改状态失败', $body->error ?: $response);
        }
    }

    /**
     * 平台设置- 智通云白名单 - 删除
     * @param $ids
     * @throws XhException
     *
     * create by fyh 20181211
     */
    public static function appServerDelWhiteList($ids)
    {
        $config = Main::getConfigByName('jAppServer');
        self::$httpClient = new HttpClient($config['url']);
        $response = self::$httpClient->delete(sprintf('/api/v1/whitelist/%s', $ids[0]));
        if (!$response->isSuccess()) {
            $body = $response->toObject();
            throw new XhException('修改状态失败', $body->error ?: $response);
        }
    }

    /**
     * 平台设置- 智通云防火墙- 列表
     * @param $page
     * @param $size
     * @return array|bool|mixed|\stdClass
     *
     * create by fyh 20181211
     */
    public static function appServerGetFirewall($page, $size)
    {
        $config = Main::getConfigByName('jAppServer');
        self::$httpClient = new HttpClient($config['url']);
        $response = self::$httpClient->get(
            '/api/v1/firewall/',
            ['page' => $page, 'size' => $size]
        );
        $body = $response->toArray();
        return $body;
    }

    /**
     * 平台设置- 智通云防火墙- 新增
     * @param $firewallInfo
     * @throws XhException
     *
     * create by fyh 20181211
     */
    public static function appServerCreateFirewall($firewallInfo)
    {
        $config = Main::getConfigByName('jAppServer');
        self::$httpClient = new HttpClient($config['url']);
        self::$httpClient->setHeader('Content-Type', 'application/json');
        $response = self::$httpClient->postJson('/api/v1/firewall/', $firewallInfo);
        if (!$response->isSuccess()) {
            $body = $response->toObject();
            throw new XhException('更新状态失败', $body->error ?: $response);
        }
    }

    /**
     * 平台设置- 智通云防火墙- 更新状态
     * @param $ids
     * @param $status
     * @throws XhException
     *
     * create by fyh 20181211
     */
    public static function appServerModifyFirewallStatus($ids, $status)
    {
        $config = Main::getConfigByName('jAppServer');
        self::$httpClient = new HttpClient($config['url']);
        $response = self::$httpClient->put(sprintf('/api/v1/firewall/%s/status', $ids[0]), ['status' => $status]);
        if (!$response->isSuccess()) {
            $body = $response->toObject();
            throw new XhException('更新状态失败', $body->error ?: $response);
        }
    }

    /**
     * 平台设置- 智通云防火墙- 修改防火墙网络类型
     * @param $id
     * @param $network
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by fyh 20181211
     */
    public static function appServerModifyFirewallNetwork($id, $network)
    {
        $config = Main::getConfigByName('jAppServer');
        self::$httpClient = new HttpClient($config['url']);
        $response = self::$httpClient->put(sprintf('/api/v1/firewall/%s/network', $id), ['network' => intval($network)]);
        $body = $response->toObject();
        if (!$response->isSuccess()) {
            throw new XhException('修改失败', $body->error ?: $response);
        }
        return $body;
    }

    /**
     * 平台设置- 智通云防火墙- 删除
     * @param $ids
     * @return bool
     * @throws XhException
     *
     * create by fyh 20181211
     */
    public static function appServerDelFirewall($ids)
    {
        $config = Main::getConfigByName('jAppServer');
        self::$httpClient = new HttpClient($config['url']);
        $response = self::$httpClient->delete(sprintf('/api/v1/firewall/%s', $ids[0]));
        if (!$response->isSuccess()) {
            $body = $response->toObject();
            throw new XhException('删除失败', $body->error ?: $response);
        }
    }

    /**
     * 平台设置- 学海浏览器白名单 - 列表
     * @param $schoolId
     * @param $userId
     * @param $key
     * @param $order
     * @param $sort
     * @return array
     *
     * create by fyh 20181212
     */
    public function schoolSiteGetSite($schoolId, $userId, $key, $order, $sort)
    {
        $builder = $this->modelsManager->createBuilder()
            ->columns('*')
            ->from('Admin\\Models\\school\\XhschoolSite')
            ->where('bDelete = 0 ')
            ->orderBy('tCreateDate desc');
        if (!User::isAdmin()) {
            if ($userId) {
                $builder->andWhere('iCreateUserId = :userId:', ['userId' => $userId]);
            }
        }
        if ($schoolId) {
            $builder->andWhere('iSchoolId = :schoolId: or bCommon = 1', ['schoolId' => $schoolId]);
        }
        if ($key) {
            $builder->andWhere('sSiteName like :key:', ['key' => '%'.$key.'%']);
        }
        if ($order && $sort) {
            $builder->orderBy(" {$sort}  {$order} ");
        }
        $data = Main::runBuilderPage($builder, self::$microEnum);
        if (count($data['rows']) > 0) {
            foreach ($data['rows'] as &$row) {
                if ($row['sImage']) {
                    $row['sImage'] = '<a target="_blank" href="'.$row['sImage'].'">查看封面</a>';
                }
            }
            unset($row);
            XhschoolInfo::runSchoolName($data['rows']);
            Main::runUserNameById($data['rows'], [
                'iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId'], true);
        }
        return $data;
    }

    /**
     * 平台设置- 学海浏览器白名单 - 表单
     * @param null $iSSId
     * @return bool
     * @throws XhException
     *
     * create by fyh 20181212
     */
    public static function schoolSiteSiteForm($iSSId = null)
    {
        $webArr = [];
        $schools = XhschoolInfo::getSchoolSupportArray(true);
        $schools[''] = '请选择学校';
        if (!User::isAdmin()) {
            $user = XhsysUser::findFirst(Main::getLoginUserInfo('userId'));
            if ($user && $user->iSchoolId) {
                $schoolId = $user->iSchoolId;
            }
        } else {
            $schoolId = 2747;
        }
        $data['schoolId'] = $schoolId;
        $data['schools'] = $schools;
        if ($iSSId) {
            $info = XhschoolSite::findFirst($iSSId);
            if (!$info) {
                throw new XhException('数据不存在');
            }
            $webArr['info'] = json_encode($info->toArray());
            if (!User::isAdmin()) {
                if (!self::schoolSiteCheckPower('edit') ||
                    $info->iCreateUserId != Main::getLoginUserInfo('userId')) {
                    $webArr['check'] = '<script>parent.$(\'#bt_modal_confirm\').hide();</script>';
                }
            }
        } else {
            if (!self::schoolSiteCheckPower('add')) {
                throw new XhException('缺少权限');
            }
        }
        $data['webArr'] = $webArr;
        return $data;
    }

    /**
     * 平台设置- 学海浏览器白名单 - 检查类型
     *
     * @param string $operate
     * @return bool
     *
     * create by fyh 20181212
     */
    public static function schoolSiteCheckPower($operate = '')
    {
        $tag = 'App_WebSite';
        if ($operate != '') {
            $tag .= '_'.ucfirst($operate); //首字母大写
        }
        return UserPower::checkUserPower($tag);
    }

    /**
     * 平台设置- 学海浏览器白名单 - 保存
     * @param $data
     * @param $fullPath
     * @return bool
     *@throws XhException
     *
     * create by fyh 20181212
     */
    public static function schoolSiteSaveSite($data, $fullPath)
    {
        if (isset($data['iSSId']) && $data['iSSId'] != '') {
            $obj = XhschoolSite::findFirst($data['iSSId']);
            if (!User::isAdmin()) {
                if (!self::schoolSiteCheckPower('edit') || $obj->iCreateUserId != Main::getLoginUserInfo('userId')) {
                    throw new XhException('缺少权限');
                }
            }
        } else {
            if (!self::schoolSiteCheckPower('add')) {
                throw new XhException('缺少权限');
            }
            $obj =  new XhschoolSite();
        }
        $obj->assign($data);
        if (!empty($fullPath)) { //有图片上传
            $url = Main::uploadToFileManageSystem($fullPath, 'img', null, true);
            @unlink($fullPath);
            $obj->sImage = $url;
        }
        if (!$obj->save()) {
            throw new XhException('保存失败');
        }
    }

    /**
     * 平台设置- 学海浏览器白名单 - 删除
     * @param $id
     * @return bool
     * @throws XhException
     *
     * create by fyh 20181212
     */
    public static function schoolSiteDelSite($id)
    {
        $obj = XhschoolSite::findFirst([
            'conditions' => 'iSSId  = :id:',
            'bind' => ['id' => $id]
        ]);
        if (!User::isAdmin() &&
            !(self::schoolSiteCheckPower('del') && $obj->iCreateUserId == Main::getLoginUserInfo('userId'))) {
            throw new XhException('缺少权限');
        }
        $obj->bDelete = 1;
        if (!$obj->save()) {
            throw new XhException('删除失败');
        }
    }

    /**
    * 获取配置列表
    *
    * @param string $type
    * @return bool|mixed|null
    *
    * create by ck 20180612
    */
    public static function getConfig($type = 'http')
    {
        $cacheKey =  'config_'.$type;
        if (Cache::exists($cacheKey)) {
            return Cache::get($cacheKey);
        }
        $params = [
          'columns'    => 'iSCId,sConfigExplain',
          'conditions' => 'bDelete = 0'
        ];
        $params['conditions'] .= " AND sConfigType = '".$type."'";
        $configList = XhsysConfig::find($params)->toArray();
        Cache::save($cacheKey, array_column($configList, 'sConfigExplain', 'iSCId'));
        return $configList;
    }
}